package com.ojoin.trade.t0loan_core.web.service.impl;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.ojoin.trade.common.constdef.IConstDef;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.exception.IPayNowException;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.TimeUtils;
import com.ojoin.trade.common.utils.UUIDUtils;
import com.ojoin.trade.common.utils.excel.ExcelTmpl;
import com.ojoin.trade.common.utils.json.JSONUtils;
import com.ojoin.trade.common.web.dao.BaseDao;
import com.ojoin.trade.common.web.service.impl.BaseServiceImpl;
import com.ojoin.trade.common_core.web.domain.TbMerchantInfo;
import com.ojoin.trade.common_core.web.domain.TbMerchantuserExceptionorder;
import com.ojoin.trade.common_core.web.service.FactoringCompanyBaseService;
import com.ojoin.trade.common_core.web.service.MerchantUserBaseService;
import com.ojoin.trade.common_core.web.service.TbMerchantInfoBaseService;
import com.ojoin.trade.common_core.web.service.TbMerchantuserExceptionorderBaseService;
import com.ojoin.trade.common_core.web.service.TransferTokenStatusService;
import com.ojoin.trade.common_core.web.service.impl.AccountBaseServiceImpl;
import com.ojoin.trade.common_core.web.service.impl.DataVersionValidationService;
import com.ojoin.trade.supplyloan_core.web.domain.TbRedo;
import com.ojoin.trade.supplyloan_core.web.service.TbRedoService;
import com.ojoin.trade.t0loan_core.web.dao.TbT0LoanTransanctionLogDao;
import com.ojoin.trade.t0loan_core.web.domain.T0LoanCheckAccountInfoVO;
import com.ojoin.trade.t0loan_core.web.domain.T0LoanTransanctionLogInfoVO;
import com.ojoin.trade.t0loan_core.web.domain.T1SettlementReport;
import com.ojoin.trade.t0loan_core.web.domain.TbT0LoanTransanctionLog;
import com.ojoin.trade.t0loan_core.web.domain.TbTxCheckAccountReportVO;
import com.ojoin.trade.t0loan_core.web.service.T0LoanFinalBaseService;
import com.ojoin.trade.t0loan_core.web.service.T0LoanTransanctionLogBaseService;

/**
 * T+0贷款操作日志服务实现
 * @author guoting
 *
 */
@Service
public class T0LoanTransanctionLogBaseServiceImpl extends BaseServiceImpl<TbT0LoanTransanctionLog> implements
		T0LoanTransanctionLogBaseService {

	@Autowired
	private TbT0LoanTransanctionLogDao dao;
	
	@Autowired
	private FactoringCompanyBaseService companyservice;
	
	@Autowired
	private MerchantUserBaseService userservice;
	
	@Autowired
	private TbMerchantInfoBaseService infoservice;
	
	@Autowired
	private T0LoanFinalBaseService loanfinalservice;
	
	@Autowired
	private AccountBaseServiceImpl accountservice;
	
	@Autowired
	private DataVersionValidationService validateService;
	
    @Autowired
    private TbRedoService tbRedoService;
    
    @Autowired
    private TbMerchantuserExceptionorderBaseService merchantuserExceptionorderBaseService;
    
	@Autowired
	private TransferTokenStatusService transtokenService;

	/**
	 * 新增T+0贷款业务账户变更操作日志记录(T0000011)
	 */
	@Override
	public int insertT0LoanTransanctionLog(HashMap<String, Object> parammap) throws BusinessException {
		throw new BusinessException("请调用insert方法执行新增操作.");
	}

	/**
	 * 查询支付商户的指定账户余额
	 * @param mhtNo
	 * @param accType
	 * @return
	 * @throws BusinessException
	 */
	private String getAccountBalanceByMhtNo(String mhtNo, String accType)
			throws BusinessException {
		return accountservice.queryBalance(mhtNo, accType);
	}

	@Override
	protected BaseDao<TbT0LoanTransanctionLog> getBaseDao() {
		return dao;
	}

	/**
	 * 查询T0贷款对账信息列表(T0000022)
	 */
	@Override
	public List<T0LoanCheckAccountInfoVO> queryAllT0LoanCheckAccountInfoList(Pageable page) throws BusinessException {
		LogUtils.getT0loanLog().info("查询T0贷款对账信息列表. pageno->" + page.getPageNumber() + ", pagesize->" + page.getPageSize());
		List<T0LoanCheckAccountInfoVO> infolist = ((TbT0LoanTransanctionLogDao) this
				.getBaseDao()).queryAllT0LoanCheckAccountInfoList(page);
		return infolist;
	}
	
	/**
	 * 查询T1贷款对账信息列表
	 */
	@Override
	public List<T0LoanCheckAccountInfoVO> queryAllTxLoanCheckAccountInfoList(String operatetype, String mhtno, String startdate, String enddate, String ismhtnosplit, Pageable page) throws BusinessException {
		LogUtils.getT0loanLog().info("查询Tx贷款对账信息列表. operation_type->" + operatetype +", mhtno->" + mhtno +", startdate->" + startdate +", enddate->" + enddate +", ismhtnosplit->" + ismhtnosplit +", pageno->" + page.getPageNumber() + ", pagesize->" + page.getPageSize());
		List<T0LoanCheckAccountInfoVO> infolist = ((TbT0LoanTransanctionLogDao) this
				.getBaseDao()).queryAllTxLoanCheckAccountInfoList(operatetype, mhtno, startdate, enddate, ismhtnosplit, page);
		return infolist;
	}
	
	@Override
	public List<T0LoanCheckAccountInfoVO> queryTotalTxLoanCheckAccountInfo(String operatetype, String mhtno, String startdate, String enddate, Pageable page) throws BusinessException {
		LogUtils.getT0loanLog().info("查询Tx贷款对账汇总信息. operation_type->" + operatetype +", mhtno->" + mhtno +", startdate->" + startdate +", enddate->" + enddate +", pageno->" + page.getPageNumber() + ", pagesize->" + page.getPageSize());
		List<T0LoanCheckAccountInfoVO> infolist = ((TbT0LoanTransanctionLogDao) this
				.getBaseDao()).queryTotalTxLoanCheckAccountInfo(operatetype, mhtno, startdate, enddate, page);
		return infolist;
	}
	
//	private void setMhtnoInfoByList(List<T0LoanCheckAccountInfoVO> infolist) {
//		//设置债权人、债务人mhtname、mobile
//		 if (infolist == null || infolist.size() == 0)
//			 return;
//		 
//		 LogUtils.getT0loanLog().info("设置商户号对应的商户名和手机号. infolistsize->" + infolist.size() + "");
//		 
//		 HashMap<String, T0LoanCheckAccountInfoVO> creditorMap = new HashMap<String, T0LoanCheckAccountInfoVO>();
//		 HashMap<String, T0LoanCheckAccountInfoVO> debtorMap = new HashMap<String, T0LoanCheckAccountInfoVO>();
//		 
//		 for(T0LoanCheckAccountInfoVO info : infolist) {
//			 creditorMap.put(info.getCreditor_mhtno(), info);
//			 debtorMap.put(info.getDebtor_mhtno(), info);
//		 }
//		 
//		 List<String> mhtnoList = new ArrayList<String>();
//		 mhtnoList.addAll(creditorMap.keySet());
//		 mhtnoList.addAll(debtorMap.keySet());
//		
//		 if (mhtnoList == null || mhtnoList.size() == 0)
//			 return;
//		 
//		 HashMap<String, MerchantUserInfo> mchUserInfoMap = userservice.getMchUserInfoMap(mhtnoList.toArray(new String[mhtnoList.size()]));
//		 if (mchUserInfoMap == null || mchUserInfoMap.size() == 0 || mchUserInfoMap.values() == null || mchUserInfoMap.values().size() == 0) 
//			 return;
//		 
//		 for(T0LoanCheckAccountInfoVO info : infolist) {
//			 if (mchUserInfoMap.get(info.getCreditor_mhtno()) != null) {
//				 info.setCreditor_mhtname(mchUserInfoMap.get(info.getCreditor_mhtno()).getMchName());
//				 info.setCreditor_mobile(mchUserInfoMap.get(info.getCreditor_mhtno()).getMobile());
//			 }
//			 
//			 if (mchUserInfoMap.get(info.getDebtor_mhtno()) != null) {
//				 info.setDebtor_mhtname(mchUserInfoMap.get(info.getDebtor_mhtno()).getMchName());
//				 info.setDebtor_mobile(mchUserInfoMap.get(info.getDebtor_mhtno()).getMobile());
//			 }
//		}
//	}

	/**
	 * 查询指定日期指定商户的贷款业务债权用户id(T0000021)
	 */
	@Override
	public TbT0LoanTransanctionLog queryCreditorInfoFromDebtorMhtNoAndDate(
			String debtor_mhtno, String creditdate) throws BusinessException {
		LogUtils.getT0loanLog().info("查询指定日期指定商户的贷款业务债权用户id. debtor_mhtno->" + debtor_mhtno + ", creditdate" + creditdate);
		 
		return ((TbT0LoanTransanctionLogDao) this
				.getBaseDao()).queryCreditorInfoFromDebtorMhtNoAndDate(debtor_mhtno, creditdate);

	}
	
	public List<T0LoanCheckAccountInfoVO> queryT0LoanBalanceInfoListByDebtorMhtno(String mhtno, Pageable page)
			throws BusinessException {
		LogUtils.getT0loanLog().info("查询指定商户的实时T+0贷款负债信息列表. mhtno->" + mhtno + ", pageno" + page.getPageNumber() + ", pagesize->" + page.getPageSize());
		
		 List<T0LoanCheckAccountInfoVO> infolist = ((TbT0LoanTransanctionLogDao) this
				.getBaseDao()).queryT0LoanBalanceInfoListByDebtorMhtno(mhtno, page);
		 
		 return infolist;
	}

	public T0LoanCheckAccountInfoVO queryTxLoanBalanceInfoByDebtorMhtno(String mhtno)
			throws BusinessException {
		LogUtils.getT0loanLog().info("查询指定商户的实时T+1贷款负债信息列表. mhtno->" + mhtno );
		
		 T0LoanCheckAccountInfoVO vo = ((TbT0LoanTransanctionLogDao) this
				.getBaseDao()).queryTxLoanBalanceInfoByDebtorMhtno(mhtno);
		 
		 return vo;
	}
	
	@Override
	public List<T0LoanTransanctionLogInfoVO> queryT0LoanTransanctionLogInfoListByDebtorMhtNo(Map param,Pageable page) throws BusinessException {
		String paramstr = JSONUtils.toJSONString(param);
		LogUtils.getT0loanLog().info("查询指定债务人的贷款历史记录. param->" + paramstr + ", pageno" + page.getPageNumber() + ", pagesize->" + page.getPageSize());
		
		List<T0LoanTransanctionLogInfoVO> infolist = ((TbT0LoanTransanctionLogDao) this
				.getBaseDao()).queryT0LoanTransanctionLogInfoListByDebtorMhtNo(param,page);

		 return infolist;
	}

	@Override
	public List<T0LoanTransanctionLogInfoVO> queryTxLoanTransanctionLogInfoListByDebtorMhtNo(String debtor_mhtno, String operation_type,Pageable page) throws BusinessException {
		LogUtils.getT0loanLog().info("查询指定债务人的Tx贷款历史记录. debtor_mhtno->" + debtor_mhtno + ", operation_type->" + operation_type + ", pageno" + page.getPageNumber() + ", pagesize->" + page.getPageSize());
		
		List<T0LoanTransanctionLogInfoVO> infolist = ((TbT0LoanTransanctionLogDao) this
				.getBaseDao()).queryTxLoanTransanctionLogInfoListByDebtorMhtNo(debtor_mhtno, operation_type, page);

		 return infolist;
	}
	
//	private void setMhtnameAndMobileByInfoList(
//			List<T0LoanTransanctionLogInfoVO> infolist) {
//		//设置债权人、债务人mhtname、mobile
//		 if (infolist == null || infolist.size() == 0)
//			 return;
//		 
//		 LogUtils.getT0loanLog().info("设置商户号对应的商户名和手机号. infolistsize->" + infolist.size() + "");
//		 
//		 HashMap<String, T0LoanTransanctionLogInfoVO> creditorMap = new HashMap<String, T0LoanTransanctionLogInfoVO>();
//		 HashMap<String, T0LoanTransanctionLogInfoVO> debtorMap = new HashMap<String, T0LoanTransanctionLogInfoVO>();
//		 
//		 for(T0LoanTransanctionLogInfoVO info : infolist) {
//			 creditorMap.put(info.getUserIdOfIPayNowOfCreditor(), info);
//			 debtorMap.put(info.getUserIdOfIPayNowOfDebtor(), info);
//		 }
//		 
//		 List<String> mhtnoList = new ArrayList<String>();
//		 mhtnoList.addAll(creditorMap.keySet());
//		 mhtnoList.addAll(debtorMap.keySet());
//		
//		 if (mhtnoList == null || mhtnoList.size() == 0)
//			 return;
//		 
//		 HashMap<String, MerchantUserInfo> mchUserInfoMap = userservice.getMchUserInfoMap(mhtnoList.toArray(new String[mhtnoList.size()]));
//		 if (MapUtils.isEmpty(mchUserInfoMap))
//			 return;
//		 
//		 for(T0LoanTransanctionLogInfoVO info : infolist) {
//			 if (mchUserInfoMap.get(info.getUserIdOfIPayNowOfCreditor()) != null) {
//				 info.setCreditor_mhtname(mchUserInfoMap.get(info.getUserIdOfIPayNowOfCreditor()).getMchName());
//				 info.setCreditor_mobile(mchUserInfoMap.get(info.getUserIdOfIPayNowOfCreditor()).getMobile());
//			 }
//			 
//			 if (mchUserInfoMap.get(info.getUserIdOfIPayNowOfDebtor()) != null) {
//				 info.setDebtor_mhtname(mchUserInfoMap.get(info.getUserIdOfIPayNowOfDebtor()).getMchName());
//				 info.setDebtor_mobile(mchUserInfoMap.get(info.getUserIdOfIPayNowOfDebtor()).getMobile());
//			 }
//		}
//	}

	@Override
	public List<T0LoanTransanctionLogInfoVO> queryTxLoanTransanctionLogNotCreditInfoList(
			Pageable page, String operatetype) throws BusinessException {
		LogUtils.getT0loanLog().info("查询所有已审核未放款的贷款日志记录. operatetype->" + operatetype + ", pageno->" + page.getPageNumber() + ", pagesize->" + page.getPageSize());
		
		 List<T0LoanTransanctionLogInfoVO> infolist = ((TbT0LoanTransanctionLogDao) this
				.getBaseDao()).queryTxLoanTransanctionLogNotCreditInfoList(page, operatetype);
		 return infolist;
	}

	@Override
	public int updateT0LoanTransanctionLogCreditStatusByID(int id,
			int creditstatus, String creditAccountBalance) throws BusinessException {
		LogUtils.getT0loanLog().info("更新放款日志状态. id->" + id + ", creditstatus->" + creditstatus);
		
		return ((TbT0LoanTransanctionLogDao) this
				.getBaseDao()).updateT0LoanTransanctionLogCreditStatusByID(id, creditstatus, creditAccountBalance);
		 
	}

	@Override
    public void lockId(int id) throws BusinessException {
        ((TbT0LoanTransanctionLogDao)this.getBaseDao()).lockid(id);

    }

    @Override
    public void lockTable() throws BusinessException {
        ((TbT0LoanTransanctionLogDao)this.getBaseDao()).lockTable();
    }

    @Override
	public List<T0LoanTransanctionLogInfoVO> queryTxSettlementListByBusidate(String operatetype, String busidate) throws BusinessException {
    	return ((TbT0LoanTransanctionLogDao)this.getBaseDao()).queryTxSettlementListByBusidate(operatetype, busidate);
    }
    
    @Override
	public T0LoanTransanctionLogInfoVO queryTxSettlementTotalByBusidate(String operatetype, String busidate) throws BusinessException {
    	return ((TbT0LoanTransanctionLogDao)this.getBaseDao()).queryTxSettlementTotalByBusidate(operatetype, busidate);
    }
    
	@Override
	public String exportTxSettlementExl(String operatetype, String busidate, OutputStream outputStream) throws BusinessException {
		
//		T0LoanTransanctionLogInfoVO vo1 = CommonUtils.creatRandomObject(T0LoanTransanctionLogInfoVO.class, null);
//		T0LoanTransanctionLogInfoVO vo2 = CommonUtils.creatRandomObject(T0LoanTransanctionLogInfoVO.class, null);
//		T0LoanTransanctionLogInfoVO vo3 = CommonUtils.creatRandomObject(T0LoanTransanctionLogInfoVO.class, null);
//		List<T0LoanTransanctionLogInfoVO> logList = new ArrayList<T0LoanTransanctionLogInfoVO>();
//		logList.add(vo1);
//		logList.add(vo2);
//		logList.add(vo3);
//		
//		T0LoanTransanctionLogInfoVO totalVO = CommonUtils.creatRandomObject(T0LoanTransanctionLogInfoVO.class, null);
		
		List<T0LoanTransanctionLogInfoVO> logList = this.queryTxSettlementListByBusidate(operatetype, busidate);
		T0LoanTransanctionLogInfoVO totalVO = this.queryTxSettlementTotalByBusidate(operatetype, busidate);
		
		String minBusiDate = "";
		String maxBusiDate = "";
		if (logList != null && logList.size() > 0) {
			minBusiDate = logList.get(0).getBusiDate();
			maxBusiDate = logList.get(logList.size()-1).getBusiDate();
			
			for(T0LoanTransanctionLogInfoVO logvo : logList) {
				logvo.setAccountTrans(CommonUtils.getFenByString(logvo.getAccountTrans()));
				logvo.setIncomeFromFee(CommonUtils.getFenByString(logvo.getIncomeFromFee()));
				logvo.setAccountClearing(CommonUtils.getFenByString(logvo.getAccountClearing()));
			}
		}
		
		if (totalVO != null) {
			totalVO.setAccountTrans(CommonUtils.getFenByString(totalVO.getAccountTrans()));
			totalVO.setIncomeFromFee(CommonUtils.getFenByString(totalVO.getIncomeFromFee()));
			totalVO.setAccountClearing(CommonUtils.getFenByString(totalVO.getAccountClearing()));
		}
		
		
		T1SettlementReport reportvo = new T1SettlementReport();
    	reportvo.setLogList(logList);
    	reportvo.setTotalVO(totalVO);
    	reportvo.setGenerateDate(TimeUtils.getCurDate());
    	reportvo.setMaxBusiDate(maxBusiDate);
    	reportvo.setMinBusiDate(minBusiDate);
    	reportvo.setOperateType(getOperateTypeShortName(operatetype));
    	int num = (logList == null) ? 0 : logList.size();
    	reportvo.setMhtNum(num + "");
    	
			
		try {
			ExcelTmpl et= new ExcelTmpl(IConstDef.T1LOAN_SETTLEMENT_REPORT, outputStream);
			et.wrapData(reportvo);
			et.closeWbook();
			if(null==totalVO){
				return "0";
			}
			return totalVO.getAccountClearing();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return "0";
	}

	private String getOperateTypeShortName(String operatetype) {
		String operatetype_shortname = "";
		if (IConstDef.T1_LOAN_CREDIT.equals(operatetype)) {
			operatetype_shortname = "T+1";
		} else if (IConstDef.T0_LOAN_CREDIT.equals(operatetype)) {
			operatetype_shortname = "T+0";
		} else if (IConstDef.D1_LOAN_CREDIT.equals(operatetype)) {
			operatetype_shortname = "D+1";
		}
		return operatetype_shortname;
	}
	
	@Override
	public int updateT0LoanTransanctionLogVO(Map<String, Object> paramsmap) throws BusinessException {
		return ((TbT0LoanTransanctionLogDao)this.getBaseDao()).updateT0LoanTransanctionLogVO(paramsmap);
	}
	
	public List<TbT0LoanTransanctionLog> queryUnRefundT0LoanTransanctionLogList(int joinuserid) throws BusinessException {
		return ((TbT0LoanTransanctionLogDao)this.getBaseDao()).queryUnRefundT0LoanTransanctionLogList(joinuserid);
	}
	
	public void drawByTransLogRefund(Integer loanlogid, String paypwd, String pagets) throws BusinessException {
		// 操作数据版本校验
		TbT0LoanTransanctionLog validateVO = new TbT0LoanTransanctionLog();
		validateVO.setId(loanlogid);
		validateService.validateVO(validateVO, pagets);
			
		TbT0LoanTransanctionLog logvo = ((TbT0LoanTransanctionLogDao)this.getBaseDao()).selectById(loanlogid);
		TbMerchantInfo debtor_info = infoservice.queryInfoByJoinId(logvo.getIdOfTbMerchantUserOfDebtor());
		
		String mhtno = logvo.getUserIdOfIPayNowOfCreditor();
		String cardId = "cradId2015102900000000000000000000000014";
		String returnamount = logvo.getRealReturnAmount();
		BigDecimal amountdecimal = new BigDecimal(returnamount);
		String amountstr = amountdecimal.divide(new BigDecimal(100)).doubleValue()+ ""; 
		String memo = "" + debtor_info.getMchName() + "还款：" + amountstr + "元";  
		
		String transToken = UUIDUtils.create();
		try {
			accountservice.drawBalanceToIpaynow(mhtno, paypwd, cardId, returnamount, transToken, memo);
		} catch(Exception e) {
			if (e instanceof IPayNowException) {
				TbRedo redo = new TbRedo();
				redo.setApplyDate(TimeUtils.getCurDate());
				redo.setOrderId(transToken);
				Map<String, Object> map = new HashMap<>();
				map.put("loanlogid", loanlogid);
				map.put("paypwd", paypwd) ;
				map.put("pagets", pagets) ;
				byte[] bytes = CommonUtils.serialize(map);
				redo.setBusinessType(logvo.getOperationType());
				redo.setParamstr(bytes);
				tbRedoService.insertTbRedo(redo);
				TbMerchantuserExceptionorder ordervo = new TbMerchantuserExceptionorder();
				ordervo.setOrderid(transToken);
				ordervo.setAccountStatus(IConstDef.ACCOUNT_STATUS_FREEZE);
				ordervo.setIdOfTbMerchantUser(logvo.getIdOfTbMerchantUserOfCreditor());
				ordervo.setBusinessType(IConstDef.EXCEPTIONORDER_TYPE_DRAW);
				ordervo.setOrderTime(TimeUtils.getCurDateTime());
				merchantuserExceptionorderBaseService.insertMerchantuserExceptionorder(ordervo);
			}
			throw new BusinessException(e);
		}
		// 更新放款日志状态为已提现
		Map<String, Object> parammap = new HashMap<String, Object>();
        parammap.put("id", logvo.getId());
        parammap.put("creditstatus", IConstDef.LOAN_DRAWED);
		this.updateT0LoanTransanctionLogVO(parammap);
		
	}
	
	public void drawByTransLogRefundRedo(Integer loanlogid, String pagets, String orderId) throws BusinessException {
		// 操作数据版本校验
		TbT0LoanTransanctionLog validateVO = new TbT0LoanTransanctionLog();
		validateVO.setId(loanlogid);
		validateService.validateVO(validateVO, pagets);
			
		TbT0LoanTransanctionLog logvo = ((TbT0LoanTransanctionLogDao)this.getBaseDao()).selectById(loanlogid);
		
		// 更新放款日志状态为已提现
		Map<String, Object> parammap = new HashMap<String, Object>();
        parammap.put("id", logvo.getId());
        parammap.put("creditstatus", IConstDef.LOAN_DRAWED);
		this.updateT0LoanTransanctionLogVO(parammap);
		
		transtokenService.updateTransferTokenStatus(orderId,IConstDef.TRANSFERSTATUS_SUCCESS,"处理成功");
        tbRedoService.updateTbRedo(orderId);
        TbMerchantuserExceptionorder ordervo=new TbMerchantuserExceptionorder();
        ordervo.setHandleTime(TimeUtils.getCurDateTime());
        ordervo.setHandleMemo("处理完毕");
        ordervo.setOrderid(orderId);
        ordervo.setAccountStatus(IConstDef.ACCOUNT_STATUS_UNFREEZE);
        merchantuserExceptionorderBaseService.updateVOByOrderId(ordervo);
        
		LogUtils.getT0loanLog().info("===============保理商户 " + logvo.getIdOfTbMerchantUserOfCreditor() + "Redo提现结束============");
		
	}

	@Override
	public List<TbT0LoanTransanctionLog> queryUnDrawT0LoanTransanctionLogList(String operatetype, Pageable page) throws BusinessException {
		return ((TbT0LoanTransanctionLogDao)this.getBaseDao()).queryUnDrawT0LoanTransanctionLogList(operatetype, page);
	}

	@Override
	public void exportTxCheckAcccountFile(String startdate, String enddate, Integer joinuserid,
			OutputStream outputStream) throws BusinessException {
		List<T0LoanCheckAccountInfoVO> calist = ((TbT0LoanTransanctionLogDao)this.getBaseDao()).queryAllTxLoanCheckAccountInfoList(null, null, startdate, enddate, null, null);
		calist = sortCheckAccountInfoVOByCreditDate(calist);
		
		if (calist != null && calist.size() > 0) {
			long totalprincipalandinterest = 0;
			long totalcreditincome = 0;
			long totalclearingamount = 0;
			for (T0LoanCheckAccountInfoVO vo : calist) {
				long principalandinterest = CommonUtils.getLong(vo.getClearingamount()) + CommonUtils.getLong(vo.getCreditincome());
				
				totalprincipalandinterest += principalandinterest;
				totalcreditincome += CommonUtils.getLong(vo.getCreditincome());
				totalclearingamount += CommonUtils.getLong(vo.getClearingamount());
				
				vo.setClearingamount(CommonUtils.getFenByString(vo.getClearingamount()));
				vo.setCreditincome(CommonUtils.getFenByString(vo.getCreditincome()));
				vo.setTransamount(CommonUtils.getFenByLong(principalandinterest));
			}
			
			TbTxCheckAccountReportVO reportvo = new TbTxCheckAccountReportVO();
			reportvo.setStartdate(startdate);
			reportvo.setEnddate(enddate);
			reportvo.setTotalclearingamount(CommonUtils.getFenByLong(totalclearingamount));
			reportvo.setTotalcreditincome(CommonUtils.getFenByLong(totalcreditincome));
			reportvo.setTotalprincipalandinterest(CommonUtils.getFenByLong(totalprincipalandinterest));
			reportvo.setCalist(calist);
			
			try {
				ExcelTmpl et = new ExcelTmpl(IConstDef.TXLOAN_CHECKACCOUNT_REPORT, outputStream);
				et.wrapData(reportvo);
				et.closeWbook();
				
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			throw new BusinessException("对账信息为空，不可导出对账单，请检查.");
		}
		
	}
	
	public List<T0LoanCheckAccountInfoVO> sortCheckAccountInfoVOByCreditDate(List<T0LoanCheckAccountInfoVO> list) {
		T0LoanCheckAccountInfoVO[] vos = list.toArray(new T0LoanCheckAccountInfoVO[0]);
		Arrays.sort(vos, new Comparator<T0LoanCheckAccountInfoVO>() {

			@Override
			public int compare(T0LoanCheckAccountInfoVO o1, T0LoanCheckAccountInfoVO o2) {
				long dateSpaceOfDay = 0;
				try {
					dateSpaceOfDay = TimeUtils.getDateSpaceOfDay(o1.getCredit_date(), o2.getCredit_date());
				} catch (Exception e) {
					e.printStackTrace();
				}
				
				if (dateSpaceOfDay > 0) {
					return -1;
				} else if (dateSpaceOfDay < 0) {
					return 1;
				} else  {
					return 0;
				}
			}

		});
		
		return Arrays.asList(vos);
	}

}
